package v1

import (
	"log"
	"net/http"
	"strconv"
	"time"

	"gitee.com/daonna/collab-manage-system/service"

	"github.com/gin-gonic/gin"
)

// CreateActivity 创建新活动
func CreateActivity(c *gin.Context) {
	// 获取当前用户ID（创建者）
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 解析请求体
	var input service.CreateActivityInput
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 设置创建者ID
	input.CreatorID = int64(currentUserID.(uint))

	// 调用服务层创建活动
	activity, err := service.CreateActivity(c.Request.Context(), input)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "创建活动失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "创建活动成功",
		"data":    activity,
	})
}

// GetActivityByID 获取指定ID的活动
func GetActivityByID(c *gin.Context) {
	// 获取活动ID
	activityID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的活动ID",
		})
		return
	}

	// 获取当前用户ID
	_, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 调用服务层获取活动信息
	activity, err := service.GetActivityByID(c.Request.Context(), activityID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取活动失败: " + err.Error(),
		})
		return
	}

	if activity == nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code":    404,
			"message": "未找到该活动",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取活动成功",
		"data":    activity,
	})
}

// ListActivities 获取活动列表
func ListActivities(c *gin.Context) {
	// 获取当前用户ID
	_, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 解析查询参数
	var input service.ListActivitiesInput
	if err := c.ShouldBindQuery(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的查询参数: " + err.Error(),
		})
		return
	}

	// 调用服务层获取活动列表
	activities, total, err := service.ListActivities(c.Request.Context(), input)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取活动列表失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":     200,
		"message":  "获取活动列表成功",
		"data":     activities,
		"total":    total,
		"page":     input.Page,
		"pageSize": input.PageSize,
	})
}

// UpdateActivity 更新活动信息
func UpdateActivity(c *gin.Context) {
	// 获取活动ID
	activityID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的活动ID",
		})
		return
	}

	// 解析请求体
	var input service.UpdateActivityInput
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 调用服务层更新活动信息
	// 注意：在服务层中应当验证当前用户是否有权限更新该活动
	updatedActivity, err := service.UpdateActivity(c.Request.Context(), activityID, input)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "更新活动失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "更新活动成功",
		"data":    updatedActivity,
	})
}

// DeleteActivity 删除活动
func DeleteActivity(c *gin.Context) {
	// 获取活动ID
	activityID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的活动ID",
		})
		return
	}

	// 调用服务层删除活动
	// 注意：在服务层中应当验证当前用户是否有权限删除该活动
	err = service.DeleteActivity(c.Request.Context(), activityID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "删除活动失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "删除活动成功",
	})
}

// UpdateActivityStatus 更新活动状态
func UpdateActivityStatus(c *gin.Context) {
	// 获取活动ID
	activityID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的活动ID",
		})
		return
	}

	// 解析请求体
	var req struct {
		Status string `json:"status" binding:"required,oneof=draft published cancelled completed"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 封装为更新请求
	input := service.UpdateActivityStatusInput{
		Status: req.Status,
	}

	// 调用服务层更新活动状态
	err = service.UpdateActivityStatus(c.Request.Context(), activityID, input)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "更新活动状态失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "更新活动状态成功",
	})
}

// JoinActivity 用户加入活动
func JoinActivity(c *gin.Context) {
	// 获取活动ID
	activityID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的活动ID",
		})
		return
	}

	// 获取当前用户ID
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 解析请求体
	var req struct {
		DepartmentID *int64 `json:"department_id"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 调用服务层加入活动
	err = service.JoinActivity(c.Request.Context(), activityID, int64(currentUserID.(uint)), req.DepartmentID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "加入活动失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "加入活动成功",
	})
}

// LeaveActivity 用户退出活动
func LeaveActivity(c *gin.Context) {
	// 获取活动ID
	activityID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的活动ID",
		})
		return
	}

	// 获取当前用户ID
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 调用服务层退出活动
	err = service.LeaveActivity(c.Request.Context(), activityID, int64(currentUserID.(uint)))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "退出活动失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "退出活动成功",
	})
}

// ListActivityParticipants 获取活动参与者列表
func ListActivityParticipants(c *gin.Context) {
	// 获取活动ID
	activityID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的活动ID",
		})
		return
	}

	// 获取当前用户ID
	_, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 解析查询参数
	var input service.ListActivityParticipantsInput
	if err := c.ShouldBindQuery(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的查询参数: " + err.Error(),
		})
		return
	}

	// 调用服务层获取参与者列表
	participants, total, err := service.ListActivityParticipants(c.Request.Context(), activityID, input)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取参与者列表失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":     200,
		"message":  "获取参与者列表成功",
		"data":     participants,
		"total":    total,
		"page":     input.Page,
		"pageSize": input.PageSize,
	})
}

// AddActivityParticipants 批量添加活动参与者
func AddActivityParticipants(c *gin.Context) {
	// 获取活动ID

	// 解析请求体
	var req struct {
		UserIDs      []int64 `json:"user_ids" binding:"required"`
		DepartmentID *int64  `json:"department_id"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
		})
		return
	}

	// TODO: 调用服务层批量添加参与者
	// 这个方法需要在 service 包中实现
	// err = service.AddActivityParticipants(c.Request.Context(), activityID, int64(currentUserID.(uint)), req.UserIDs, req.DepartmentID)

	// 临时响应
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "添加参与者成功",
		"data": gin.H{
			"success_count": len(req.UserIDs),
			"failed_count":  0,
		},
	})
}

// UploadActivityAttachment 上传活动附件
func UploadActivityAttachment(c *gin.Context) {
	// 获取活动ID
	activityID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的活动ID",
		})
		return
	}

	// 接收上传的文件
	file, header, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的文件上传: " + err.Error(),
		})
		return
	}
	defer file.Close()

	// 获取文件描述（可选）
	description := c.PostForm("description")

	// TODO: 调用服务层上传附件
	// 这个方法需要在 service 包中实现
	// attachment, err := service.UploadActivityAttachment(c.Request.Context(), activityID, int64(currentUserID.(uint)), file, header.Filename, header.Size, description)

	// 临时响应
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "上传附件成功",
		"data": gin.H{
			"id":           123, // 示例ID
			"activity_id":  activityID,
			"filename":     header.Filename,
			"size":         header.Size,
			"content_type": "application/octet-stream", // 示例类型
			"description":  description,
			"uploaded_at":  time.Now(),
			"url":          "http://example.com/uploads/" + header.Filename, // 示例URL
		},
	})
}

// ListActivityAttachments 获取活动附件列表
func ListActivityAttachments(c *gin.Context) {
	// 获取活动ID
	activityID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的活动ID",
		})
		return
	}

	// 获取当前用户ID
	_, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// TODO: 调用服务层获取附件列表
	// 这个方法需要在 service 包中实现
	// attachments, err := service.ListActivityAttachments(c.Request.Context(), activityID)

	// 临时响应
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取附件列表成功",
		"data": []gin.H{
			{
				"id":           123,
				"activity_id":  activityID,
				"filename":     "示例文件.pdf",
				"size":         12345,
				"content_type": "application/pdf",
				"description":  "活动说明文档",
				"uploaded_at":  time.Now().Add(-24 * time.Hour),
				"url":          "http://example.com/uploads/示例文件.pdf",
			},
		},
	})
}

// DeleteActivityAttachment 删除活动附件
func DeleteActivityAttachment(c *gin.Context) {
	// 获取活动ID和附件ID

	// TODO: 调用服务层删除附件
	// 这个方法需要在 service 包中实现
	// err = service.DeleteActivityAttachment(c.Request.Context(), activityID, attachmentID, int64(currentUserID.(uint)))

	// 临时响应
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "删除附件成功",
	})
}

// GetActivityStatistics 获取活动统计信息
func GetActivityStatistics(c *gin.Context) {
	// 获取活动ID
	activityID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的活动ID",
		})
		return
	}

	// 获取当前用户ID
	_, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// TODO: 调用服务层获取统计信息
	// 这个方法需要在 service 包中实现
	// stats, err := service.GetActivityStatistics(c.Request.Context(), activityID)

	// 临时响应
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取活动统计信息成功",
		"data": gin.H{
			"activity_id":  activityID,
			"total_joined": 42,
			"total_left":   3,
			"department_stats": []gin.H{
				{
					"department_id":   1,
					"department_name": "技术部",
					"count":           20,
				},
				{
					"department_id":   2,
					"department_name": "市场部",
					"count":           15,
				},
				{
					"department_id":   3,
					"department_name": "人事部",
					"count":           7,
				},
			},
		},
	})
}

// GetActivityCalendar 获取活动日历视图
func GetActivityCalendar(c *gin.Context) {
	// 获取当前用户ID
	_, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 解析时间范围参数
	startStr := c.Query("start_date")
	endStr := c.Query("end_date")

	var startDate, endDate time.Time
	var err error
	if startStr != "" {
		startDate, err = time.Parse("2006-01-02", startStr)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    400,
				"message": "无效的开始日期格式",
			})
			return
		}
	} else {
		// 默认为当月第一天
		now := time.Now()
		startDate = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
	}

	if endStr != "" {
		endDate, err = time.Parse("2006-01-02", endStr)
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    400,
				"message": "无效的结束日期格式",
			})
			return
		}
	} else {
		// 默认为下月第一天
		now := time.Now()
		nextMonth := now.Month() + 1
		year := now.Year()
		if nextMonth > 12 {
			nextMonth = 1
			year++
		}
		endDate = time.Date(year, nextMonth, 1, 0, 0, 0, 0, now.Location())
	}

	log.Println(startDate, endDate)

	// TODO: 调用服务层获取活动日历数据
	// 这个方法需要在 service 包中实现
	// activities, err := service.GetActivityCalendar(c.Request.Context(), startDate, endDate)

	// 临时响应
	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取活动日历成功",
		"data": []gin.H{
			{
				"id":         1,
				"name":       "团队建设活动",
				"start_time": time.Now().Add(24 * time.Hour),
				"end_time":   time.Now().Add(48 * time.Hour),
				"location":   "会议室A",
				"category":   "team_building",
				"is_joined":  true,
				"status":     "published",
			},
			{
				"id":         2,
				"name":       "技术培训",
				"start_time": time.Now().Add(72 * time.Hour),
				"end_time":   time.Now().Add(96 * time.Hour),
				"location":   "培训中心",
				"category":   "training",
				"is_joined":  false,
				"status":     "published",
			},
		},
	})
}
